app.controller('ProductOneCtrl', ['$scope', '$timeout', '$http', '$compile', 'toaster', '$location', '$modal', 'R', 'FileUploader', '$q', '$rootScope',
function($scope, $timeout, $http, $compile, toaster, $location, $modal, R, FileUploader, $q, $rootScope) {
    
    function initEditor(content){
        var editor = UE.getEditor('myEditor'+$scope.editorid,{
            toolbars:[['fullscreen', 'source', '|', 'undo', 'redo', '|',
            'bold', 'italic', 'underline', 'strikethrough', 'removeformat', 'formatmatch', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
            'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
            'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
            'indent', '|',
            'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|',
            'link', 'unlink', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
            'simpleupload', 'pagebreak', 'background', 'insertvideo', '|',
            'horizontal', 'date', 'time', 'snapscreen', '|',
            'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|',
            'print', 'preview', 'searchreplace', 'drafts', 'help']],
            autoClearinitialContent:true,
            autoHeightEnabled: false,
            wordCount:false,
            elementPathEnabled:false,
            initialFrameHeight:800,
            serverUrl: R.getFileUpload(),
            imageActionName: 'uploadImage',
            imageFieldName: 'inputFile',
            imageFieldTypeValue: 1
        });

        editor.ready(function(){
            UE.getEditor('myEditor'+$scope.editorid).setContent(content);
        });
    }

    $scope.editorid = Math.floor(Math.random()*10000);

    var urlparams = $location.search();
    $scope.id = urlparams.id;

    if ($scope.id) {
        R.getProductDetailById({id: $scope.id}).then(function(data){
            $scope.item = data.bizData;

            setTimeout(function(){
                initEditor($scope.item.comment);
            }, 1000);

            $scope.model.priceRange = $scope.item.priceRange.split('-');
            $scope.model.tags = $scope.item.tags;
        });
    }else{
        $scope.item = {
        	mockScanNum: 0,
        	mockDealNum: 0,
            checkState: 0,
            comment: '',
            companyName: '',
            productName: '',
            isDisplay: 0,
            isDiscount: 0,
            order: 0,
            phone: '',
        }

        setTimeout(function(){
            initEditor('');
        }, 1000);
    }

    R.getRecomandIndex({type: 0}).then(function(data){
        $scope.mappers.order = data.bizData;
    });

    $scope.mappers = {
        classifyId: [],
        directionId: [],
        order: [],
        checkState: [{
            'id': 0,
            'name': '未审核'
        },{
            'id': 1,
            'name': '已审核'
        }],
        isDisplay: [{
            'id': 0,
            'name': '否'
        },{
            'id': 1,
            'name': '是'
        }],
        isDiscount: [{
            'id': 0,
            'name': '不优惠'
        },{
            'id': 1,
            'name': '优惠'
        }],
        recommandTags: []
    }

    $scope.model = {
        priceRange: [0, 0],
        tags: []
    }

    R.getAllClassifyAndDirection().then(function(data){
        $scope.mappers.classifyId = data.bizData.classifys;
        $scope.mappers.directionId = data.bizData.directions;
    });

    $scope.uploader = new FileUploader({
        url: R.getFileUpload(),
        formData: [{
            type: 0
        }],
        autoUpload: true,
        alias: 'inputFile'
    });

    $scope.uploader.onCompleteItem = function(res, data){
        $scope.item.coverPic = data.bizData.attachmentUrl;
        $scope.item.attachmentUrl = data.bizData.attachmentUrl;
        $scope.item.attachmentName = data.bizData.attachmentName;
        $scope.item.attachmentSize = data.bizData.attachmentSize;
    };

    R.getRecomandTags({type: 0}).then(function(data){
        $scope.mappers.recommandTags = data.bizData;
    });

    $scope.addTag = function(tag){
        var deferred = $q.defer();

        R.saveTag({
            "tagName": tag.name,
            "type": 0
        }).then(function(data){
            deferred.resolve({id: data.bizData.id, name: tag.name});
        });

        return deferred.promise;
    }

    $scope.addTags = function(tag){
        var flag = false;
        angular.forEach($scope.model.tags, function(i){
            if (i.id == tag.id){
                flag = true;
            }
        });
        if (flag) return;

        $scope.model.tags.push({
            id: tag.id,
            name: tag.tagName
        });
    }

    $scope.opened = [];
    $scope.open = function($event,index) {
        $event.preventDefault();
        $event.stopPropagation();
        $scope.opened[index] = true;
    };

    $scope.submit = function(){
        $scope.item.publishTime = R.getTimeFormat($scope.item.publishTime || new Date(), 'yyyy-MM-dd');
        
        if (!$scope.model.priceRange[0]){
            $scope.model.priceRange[0] = 0;
        }
        if (!$scope.model.priceRange[1]){
            $scope.model.priceRange[1] = 0;
        }
        $scope.item.priceRange = $scope.model.priceRange.join('-');

        $scope.item.tagIds = [];
        angular.forEach($scope.model.tags, function(item){
            $scope.item.tagIds.push(item.id);
        });
        $scope.item.tagIds = $scope.item.tagIds.join(',');

        $scope.item.comment = UE.getEditor('myEditor'+$scope.editorid).getContent();

        if ($scope.item.id){
            R.updateProduct($scope.item).then(function(data){
                toaster.success("操作成功");
                $location.url("/app/product/list");
            });
        }else{
			var user = $rootScope.getSgObj('LOGINUSER');
          
            $scope.item.userId = user.id;
            R.addProduct($scope.item).then(function(data){
                toaster.success("操作成功");
                $location.url("/app/product/list");
            });
        }
    }

}]);